'use strict';

app.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/index', {
        templateUrl: 'indexbase.html',
        controller: 'IndexCtrl'
    }).when('/products', {
        templateUrl: 'products.html',
        controller: 'ProductsCtrl'
    }).when('/demands', {
        templateUrl: 'demands.html',
        controller: 'DemandsCtrl'
    }).when('/mypublic', {
        templateUrl: 'mypublic.html',
        controller: 'MyPublicsCtrl'
    }).when('/mybox', {
        templateUrl: 'mybox.html',
        controller: 'MyBoxCtrl'
    }).when('/me', {
        templateUrl: 'me.html',
        controller: 'MeCtrl'
    }).when('/me_edit', {
        templateUrl: 'me-edit.html',
        controller: 'MeEditCtrl'
    }).when('/create_demand', {
        templateUrl: 'create_demand.html',
        controller: 'CreateDemandCtrl'
    }).when('/create_product', {
        templateUrl: 'create_product.html',
        controller: 'CreateProductCtrl'
    }).when('/product', {
        templateUrl: 'product.html',
        controller: 'ProductCtrl'
    }).when('/demand', {
        templateUrl: 'demand.html',
        controller: 'DemandCtrl'
    }).when('/scanapply', {
        templateUrl: 'scanapply.html',
        controller: 'ScanApplyCtrl'
    }).otherwise('/index');
});

app.controller('AppCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
        $rootScope.getSgObj = function(key) {
            var obj = $window.sessionStorage.getItem(key);
            return JSON.parse(obj);
        }
        $rootScope.setSgObj = function(key, value) {
            return $window.sessionStorage.setItem(key, JSON.stringify(value));
        }

        $rootScope.user = $scope.user = $rootScope.getSgObj('LOGINUSER');

        $scope.logout = function(){
        	R.loginOut().then(function(){
        		$rootScope.setSgObj('LOGINUSER', null);
        		window.location.reload();
        	});
        }

        $scope.$on('$routeChangeStart', function(i, n, c){
        	if (n && n.$$route){
        		$scope.currentpath = n.$$route.originalPath;
        		if ($(".menu").hasClass('ssm-nav-visible')){
        			$(".ssm-overlay").trigger('click');
        		}
        	}
        });

        $('.menu').slideAndSwipe();

		var subUrl;
		if (window.location.href.indexOf("#") > 0)
		{
			subUrl = location.href.split("#")[0];
		}else {
			subUrl = window.location.href;
		}

		R.getTicketMap({'url': subUrl
		}).then(function (data) {
			$scope.data = data.bizData;
			wx.config({
				debug: false,
				appId: $scope.data.appId,
				timestamp: $scope.data.timestamp,
				nonceStr: $scope.data.noncestr,
				signature:  $scope.data.signature,
				jsApiList: [
					'checkJsApi',
					'onMenuShareTimeline',
					'onMenuShareAppMessage'
				]
			});
			wx.ready(function () {
				wx.onMenuShareAppMessage({
					title: '象呈-AR/VR优质供应商', // 分享标题
					desc: '提供最优最全的AR/VR产品，专人对接项目需求', // 分享描述
					link: 'http://xc.arinchina.com/ar-mobile/', // 分享链接
					imgUrl: 'http://xc.arinchina.com/ar-mobile/images/getheadimg.jpeg', // 分享图标
					type: 'link', // 分享类型,music、video或link，不填默认为link
					dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
					success: function () {
						alert('分享成功');
					},
					cancel: function () {
						alert('分享失败');
					}
				});
				wx.onMenuShareTimeline({
					title: '象呈-AR/VR优质供应商', // 分享标题
					link: 'http://xc.arinchina.com/ar-mobile/', // 分享链接
					imgUrl: 'http://xc.arinchina.com/ar-mobile/images/getheadimg.jpeg', // 分享图标
					success: function () {
						alert('分享成功');
					},
					cancel: function () {
						alert('分享失败');
					}
				});
			});
		})
    }
	
	
]);

app.controller('IndexCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	$scope.user = $rootScope.user;
    	$('.index').height($(window).height() - $(".header").height());
    
        R.getIndexProducts().then(function(data){
        	$scope.products = data.bizData;
        });

        R.getIndexDemands().then(function(data){
        	$scope.demands = data.bizData;
        });
    }
]);

app.controller('ProductsCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	$scope.mappers = {
    	};

    	$scope.params = {
    		classifyId: -1,
    		directionId: -1,
    		address: -1,
    		isDiscount: -1,
    		pageNo: -1,
    		pageSize: 8,
            keyword: ""
    	}

    	R.getAllClassifyAndDirection().then(function(data){
    		$scope.mappers.classifyId = [{id:-1, name:'全部分类'}].concat(data.bizData.classifys);
    		$scope.mappers.directionId = [{id:-1, name:'全部分类'}].concat(data.bizData.directions);
    	});

    	R.getAddressList().then(function(data){
    		$scope.mappers.address = data.bizData;
    	});

    	$scope.products = [];

    	$scope.loading = false;
    	$scope.loadData = function(){
    		if ($scope.loading) return;
    		if ($scope.params.pageNo * $scope.params.pageSize > $scope.sum) return;
    		$scope.params.pageNo++;
    		$scope.loading = true;
    		R.getProductList($scope.params).then(function(data){
				$scope.products = $scope.products.concat(data.bizData.list);
				$scope.sum = data.bizData.count;
				$scope.loading = false;
    		});
    	}
    }
]);

app.controller('DemandsCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	$scope.mappers = {
    	};

    	$scope.params = {
    		classifyId: -1,
    		directionId: -1,
    		address: -1,
    		isDiscount: -1,
    		pageNo: -1,
    		pageSize: 8,
    		authState: -1,
            keyword: '',
    		recruitState: -1
    	}

    	R.getAllClassifyAndDirection().then(function(data){
    		$scope.mappers.classifyId = [{id:-1, name:'全部分类'}].concat(data.bizData.classifys);
    		$scope.mappers.directionId = [{id:-1, name:'全部分类'}].concat(data.bizData.directions);
    	});

    	R.getAddressList().then(function(data){
    		$scope.mappers.address = data.bizData;
    	});

    	$scope.demands = [];

    	$scope.loading = false;
    	$scope.loadData = function(){
    		if ($scope.loading) return;
    		if ($scope.params.pageNo * $scope.params.pageSize > $scope.sum) return;
    		$scope.params.pageNo++;
    		$scope.loading = true;
    		R.getDemandList($scope.params).then(function(data){
				$scope.demands = $scope.demands.concat(data.bizData.list);
				$scope.sum = data.bizData.count;
				$scope.loading = false;
    		});
    	}
    }
]);

app.controller('MyPublicsCtrl', ['$scope', '$window', '$rootScope', 'R', '$location',
    function($scope, $window, $rootScope, R, $location) {
    	var sobj = $location.search();
        var type = sobj.type;
        if (type && type == 1) {
            $scope.activetype = 1;
        }else{
            $scope.activetype = 0;
        }
        

    	$scope.params = {
    		"userId": $rootScope.user.id,
			"pageNo": -1,
			"pageSize": 8
    	}

    	$scope.$watch("activetype", function(newval, oldval){
    		if (oldval != null){
    			$scope.items = [];
    			$scope.params.pageNo = -1;
    			$scope.loadData();
    		}
    	});

    	$scope.items = [];

    	$scope.loading = false;
    	$scope.loadData = function(){
    		if ($scope.loading) return;
    		if ($scope.params.pageNo * $scope.params.pageSize > $scope.sum) return;
    		$scope.params.pageNo++;
    		$scope.loading = true;
			
			if ($scope.activetype == 1){
		    	R.getDemandsByUserId($scope.params).then(function(data){
					$scope.items = $scope.items.concat(data.bizData.list);
					$scope.sum = data.bizData.count;
					$scope.loading = false;
				});
		    }else{
		    	R.getProductsByUserId($scope.params).then(function(data){
					$scope.items = $scope.items.concat(data.bizData.list);
					$scope.sum = data.bizData.count;
					$scope.loading = false;
				});
		    }
    	}
    }
]);

app.controller('MyBoxCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	$scope.params = {
    		"userId": $rootScope.user.id,
    	}

    	$scope.items = [];

    	$scope.loading = false;
    	$scope.loadData = function(){
    		if ($scope.loading) return;
    		if ($scope.params.pageNo * $scope.params.pageSize > $scope.sum) return;
    		$scope.params.pageNo++;
    		$scope.loading = true;
			
	    	R.getMsgsByUserId($scope.params).then(function(data){
				$scope.items = $scope.items.concat(data.bizData);
				$scope.loading = false;
			});
    	}

    	$scope.loadData();
    }
]);

app.controller('MeCtrl', ['$scope', '$window', '$rootScope', 'R', '$location', 'FileUploader',
    function($scope, $window, $rootScope, R, $location, FileUploader) {
        var sobj = $location.search();
        var id = sobj.id;

        $scope.id = id;

        if ($scope.id){
            var id = $scope.id;
            $scope.others = true;
        }else{
            id = $scope.user.id;
        }

        if (!id) {
            window.location.href = '';
        }

    	R.getUserInfoById({userId: id}).then(function(data){
			$scope.item = data.bizData;
		});
    }
]);


app.controller('MeEditCtrl', ['$scope', '$window', '$rootScope', 'R', 'FileUploader',
    function($scope, $window, $rootScope, R, FileUploader) {
    	$scope.mappers = {
    		address: null
    	}

    	R.getAddressList().then(function(data){
	        $scope.mappers.address = data.bizData;

        	R.getUserInfoById({userId: $rootScope.user.id}).then(function(data){
                $scope.item = data.bizData;

                if ($scope.item.countryId){
		    		angular.forEach($scope.mappers.address, function(item){
		                if (item.id == $scope.item.countryId){
		                    $scope.model.l1 = item;
		                
		                    if ($scope.item.provinceId){
		                        angular.forEach(item.childs, function(item){
		                            if (item.id == $scope.item.provinceId){
		                                $scope.model.l2 = item;

		                                if ($scope.item.cityId){
		                                    angular.forEach(item.childs, function(item){
		                                        if (item.id == $scope.item.cityId){
		                                            $scope.model.l3 = item;
		                                        }
		                                    });
		                                }
		                            }
		                        });
		                    }
		                }
		            });
		    	}

	                
	        });
		});

		$scope.model = {
	        l1: null,
	        l2: null,
	        l3: null,
	    }


        $scope.uploader = new FileUploader({
            url: R.getFileUpload(),
            formData: [{
                type: 1
            }],
            autoUpload: true,
            alias: 'inputFile'
        });

        $scope.uploader.onCompleteItem = function(res, data){
            $scope.item.icon = data.bizData.attachmentUrl;
            $scope.item.attachmentUrl = data.bizData.attachmentUrl;
            $scope.item.attachmentName = data.bizData.attachmentName;
            $scope.item.attachmentSize = data.bizData.attachmentSize;
        };

	    $scope.$watch('model.l1', function(newval){
	    	if (newval && $scope.model.l2.parentId != newval.id){
	        	$scope.model.l2 = null;
	        }
	    });

	    $scope.$watch('model.l2', function(newval){
	        if (newval && $scope.model.l3.parentId != newval.id){
	        	$scope.model.l3 = null;
	        }
	    });

		$scope.submit = function(){
			if ($scope.model.l1) {
        		$scope.item.countryId = $scope.model.l1.id;
	        }
	        if ($scope.model.l2) {
	        	$scope.item.provinceId = $scope.model.l2.id;
	        }
	        if ($scope.model.l3) {
	        	$scope.item.cityId = $scope.model.l3.id;
	        }

			R.updateUserInfo($scope.item).then(function(data){
				alert('保存成功');
			});
		}
    }
]);

app.controller('CreateProductCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	
    	$scope.item = {
    		productName: '',
    		companyName: '',
    		phone: '',
    		comment: '',
    		attachmentUrl: '',
    		userId: $rootScope.user.id
    	}

		$scope.create = function(){
            if (!$scope.item.productName) {
                alert('请输入产品标题');
                return;
            }
			R.publishProduct($scope.item).then(function(data){
				if (data.rtnCode == '0000000'){
                    alert('发布成功');
                    window.location.href = '#!/mypublic?type=0';
                }else{
                    alert('输入的内容有误，请核实后再提交');
                }
			});
		}
    }
]);

app.controller('ProductCtrl', ['$scope', '$window', '$rootScope', 'R', '$location',
    function($scope, $window, $rootScope, R, $location) {
        window.scrollTo(0, 0);

        var sobj = $location.search();
        var id = sobj.id;
        if (!id) {
            window.location.href = '';
        }
        $scope.id = id;
        $scope.user = $rootScope.user;
        $scope.appling = false;

        R.getProductDetailById({id: id}).then(function(data){
            $scope.item = data.bizData;
        });

        $scope.sendApply = function(){
            if ($scope.comment.length < 20){
                alert('至少输入20字');
                return;
            }
            R.sendApplyIntention({
                userId: $scope.user.id,
                targetId: id,
                type: 0,
                comment: $scope.comment
            }).then(function(data){
                window.location.reload();
            })
        }
    }
]);

app.controller('DemandCtrl', ['$scope', '$window', '$rootScope', 'R', '$location',
    function($scope, $window, $rootScope, R, $location) {
        window.scrollTo(0, 0);
        
        var sobj = $location.search();
        var id = sobj.id;
        if (!id) {
            window.location.href = '';
        }
        $scope.id = id;
        $scope.user = $rootScope.user;
        $scope.appling = false;

        R.getDemandDetailById({id: id}).then(function(data){
            $scope.item = data.bizData;
        });

        $scope.sendApply = function(){
            if ($scope.comment.length < 20){
                alert('至少输入20字');
                return;
            }
            R.sendApplyIntention({
                userId: $scope.user.id,
                targetId: id,
                type: 1,
                comment: $scope.comment
            }).then(function(data){
                window.location.reload();
            });
        }
    }
]);

app.controller('ScanApplyCtrl', ['$scope', '$window', '$rootScope', 'R', '$location',
    function($scope, $window, $rootScope, R, $location) {
        window.scrollTo(0, 0);
        
        var sobj = $location.search();
        var id = sobj.id;
        var type = sobj.type;
        if (!id) {
            window.location.href = '';
        }
        $scope.user = $rootScope.user;

        R.checkApplyUserList({targetId: id, type: type}).then(function(data){
            $scope.items = data.bizData;
        });
    }
]);

app.controller('CreateDemandCtrl', ['$scope', '$window', '$rootScope', 'R',
    function($scope, $window, $rootScope, R) {
    	$scope.mappers = {
	        classifyId: [],
	        directionId: []
	    }

	    $scope.model = {
	        l1: null,
	        l2: null,
	        l3: null,
	        c1: null,
	        c2: null,
	        priceRange: [],
	        jobRange: [0],
	    }

		R.getAllClassifyAndDirection().then(function(data){
	        $scope.mappers.directionId = data.bizData.directions;
	    });

        R.getAllClassify().then(function(data){
            $scope.mappers.classifyId = data.bizData;
        });
		
		R.getAddressList().then(function(data){
        	$scope.mappers.address = data.bizData;
            $scope.model.l1 = $scope.mappers.address[0];
		}); 

	    $scope.$watch('model.l1', function(){
	        $scope.model.l2 = null;
	    });

	    $scope.$watch('model.l2', function(){
	        $scope.model.l3 = null;
	    });

	   	$scope.$watch('model.c1', function(){
	        $scope.model.c2 = null;
	    });

    	$scope.item = {
    		demandName: '',
    		priceRange: '',
    		jobRange: '',
    		address: '',
    		companyName: '',
    		phone: '',
    		comment: '',
    		classifyId: '',
    		directionId: '',
    		attachmentUrl: '',
    		userId: $rootScope.user.id
    	}

		$scope.create = function(){
			var adds = [];
	        if ($scope.model.l1) {
	            adds.push($scope.model.l1.name);
	        }
	        if ($scope.model.l2) {
	            adds.push($scope.model.l2.name);
	        }
	        if ($scope.model.l2) {
	            adds.push($scope.model.l2.name);
	        }
	        $scope.item.address = adds.join('-');

	        if ($scope.model.c2) {
	        	$scope.item.classifyId = $scope.model.c2.id;
	        }else{
	        	$scope.item.classifyId = -1;
	        }

	        $scope.item.priceRange = $scope.model.priceRange.join('-');
	        $scope.item.jobRange = $scope.model.jobRange.join('-');

			R.publishDemand($scope.item).then(function(data){
                if (data.rtnCode == '0000000'){
				    alert('发布成功');
				    window.location.href = '#!/mypublic?type=1';
                }else{
                    alert('输入的内容有误，请核实后再提交');
                }
			});
		}
    }
]);